package com.ruoyi.web.controller.business;

import cn.hutool.core.util.RandomUtil;
import com.ruoyi.business.domain.CivilServants;
import com.ruoyi.business.domain.vo.ResumeVo;
import com.ruoyi.business.service.ResumeService;
import com.ruoyi.business.utils.Excel2PdfUtil;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;


/**
 * 个人简历相关控制器
 */
@RestController
@RequestMapping("/resume")
@Api(tags = {"个人简历相关控制器"})
public class ResumeController extends BaseController {


    @Value("${fileTemplate}")
    private String fileTemplate;

    @Value("${tempFolder}")
    private String tempFolder;

    @Autowired
    ResumeService resumeService;

    @PostMapping
    @ApiOperation("个人简历生成PDF接口")
    public AjaxResult resumeToPdf(@RequestBody ResumeVo resumeVo) throws IOException {
        String randomName = RandomUtil.randomNumbers(10);
        String newExcel = resumeService.createNewExcel(resumeVo, fileTemplate,randomName);
        String pdfName = Excel2PdfUtil.excel2pdf(newExcel, tempFolder, randomName+".pdf");
        Object data=tempFolder+pdfName;
        return success(data);
    }

    @GetMapping("/download")
    @ApiOperation("个人简历PDF下载")
    public ResponseEntity<?> downloadResume(@RequestParam("pdfLocation") String pdfLocation) {
        try {
            // 读取PDF文件为字节数组
            byte[] pdfBytes = Files.readAllBytes(Paths.get(pdfLocation));

            // 设置响应头，指示这是一个要下载的文件
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=resume.pdf");
            headers.add(HttpHeaders.CONTENT_TYPE, "application/pdf");

            // 返回响应实体，包含PDF文件的字节内容和响应头
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(pdfBytes);
        } catch (IOException e) {
            // 处理异常，返回错误信息或自定义的错误响应
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("文件下载失败，请稍后重试");
        }
    }

    @DeleteMapping("/remove")
    @ApiOperation("删除服务器个人简历缓存接口")
    public AjaxResult removeResume(@RequestParam("location")String location) {
        boolean result = resumeService.removeResume(location);
        return success(result);
    }
}
